package com.sinoglobal.ningxia.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.view.listener.AbOnListViewListener;
import com.ab.view.pullview.AbPullListView;
import com.alibaba.fastjson.JSON;
import com.orhanobut.logger.Logger;
import com.sinoglobal.networkconnections.ResultCallback;
import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.adapter.ExamplePagerAdapter;
import com.sinoglobal.ningxia.adapter.NewsAdapter;
import com.sinoglobal.ningxia.adapter.NewsBannerPagerAdapter;
import com.sinoglobal.ningxia.beans.NewsBannerVo;
import com.sinoglobal.ningxia.beans.NewsListVo2;
import com.sinoglobal.ningxia.beans.NewsSectionVo2;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.frame.AbstractActivity;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.http.Code;
import com.sinoglobal.ningxia.utils.EquipmentUtil;
import com.sinoglobal.ningxia.utils.ItktLog;
import com.sinoglobal.ningxia.widget.ChildViewPager;
import com.zhy.http.okhttp.OkHttpUtils;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.CommonPagerTitleView;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhourihu
 * @createdate 2014年7月9日 下午3:21:54
 * @Description: TODO(用一句话描述该类做什么) 新闻首页的各个板块展示
 */
public class NewsFragment extends Fragment implements AbOnListViewListener {
    private AbPullListView mListView;
    ChildViewPager headPager;
    RadioGroup radioGroup;
    ArrayList<RadioButton> radioButtons = new ArrayList<RadioButton>();// 存放banner里的
    // //
    // radiobutton。
    TextView tvPageInfo;
    NewsBannerPagerAdapter newsBannerPagerAdapter;// 广告的适配器
    NewsAdapter newsAdapter;
    ProgressDialog progressDialog;
    NewsSectionVo2 newsSectionVo;
    int pageNo, pageSize = 20;
    int currentPagePosition;// 当前页的位置
    View headView;
    private LinearLayout llWuXian;
    private MagicIndicator mcIndicator;
    private CommonNavigatorAdapter commonNavigatorAdapter;

    private ArrayList<String> titleList = new ArrayList();//子标题List
    private ExamplePagerAdapter mExamplePagerAdapter;
    private ViewPager mViewPager;
    private List<NewsSectionVo2.ListBean> childList;

    public String mClassId = "";
    public String mZclassId = "";
    private ResultCallback newsListVoCallback;

    /**
     * @param newsSectionVo
     * @return
     * @author zhourihu
     * @createdate 2014年7月9日 下午6:29:17
     * @Description: (用一句话描述该方法做什么)多例模式构造
     */
    public static NewsFragment newInstance(NewsSectionVo2 newsSectionVo) {
        NewsFragment newsFragment = new NewsFragment();
        newsFragment.newsSectionVo = newsSectionVo;
        return newsFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // Auto-generated method stub
        super.onCreate(savedInstanceState);
        ItktLog.i("NewsFragment.onCreate");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news, null);

        llWuXian = (LinearLayout) view.findViewById(R.id.ll_news_wuxian);
        mcIndicator = (MagicIndicator) view.findViewById(R.id.mc_news_indicator);
        mViewPager = (ViewPager) view.findViewById(R.id.view_pager);

        mClassId = newsSectionVo.getClassid();//设置父ID
        if (newsSectionVo.getList() != null && newsSectionVo.getList().size() != 0) {
            mZclassId = newsSectionVo.getList().get(0).getClassid();//设置子的ID
        }
        Logger.i("父的ID:" + mClassId + "**子的ID:" + mZclassId);
        int ischild = newsSectionVo.getIschild();
        switch (ischild) {
            case 0://没有子分类
                llWuXian.setVisibility(View.GONE);
                break;
            case 1://有子分类
                childList = newsSectionVo.getList();
                if (childList != null && childList.size() != 0) {
                    mZclassId = childList.get(0).getClassid();//设置子的Classid
                    for (NewsSectionVo2.ListBean childBean : childList) {
                        titleList.add(childBean.getClass_name());
                    }
                    llWuXian.setVisibility(View.VISIBLE);
                    initIndicator();
                }
                break;
            default:
                llWuXian.setVisibility(View.GONE);
                break;
        }


        mListView = (AbPullListView) view.findViewById(R.id.lv1);
        mListView.getHeaderView().setHeaderProgressBarDrawable(this.getResources().getDrawable(R.drawable.progress_circular));
        mListView.getFooterView().setFooterProgressBarDrawable(this.getResources().getDrawable(R.drawable.progress_circular));
        mListView.setAbOnListViewListener(this);
        TextView tvEmpty = (TextView) view.findViewById(R.id.tv1);
        tvEmpty.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                loadData(true, mClassId, mZclassId);

            }
        });
        mListView.setEmptyView(tvEmpty);
        headView = inflater.inflate(R.layout.head_banner, null);
        radioGroup = (RadioGroup) headView.findViewById(R.id.rg1);
        radioGroup.removeAllViews();
        tvPageInfo = (TextView) headView.findViewById(R.id.viewPager_info);
        tvPageInfo.setText(null);
        headPager = (ChildViewPager) headView.findViewById(R.id.Banner_ViewPager);
        int screentWidth = getResources().getDisplayMetrics().widthPixels;
        headPager.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, screentWidth / 2));
        newsBannerPagerAdapter = new NewsBannerPagerAdapter(getActivity(), null);
        headPager.setAdapter(newsBannerPagerAdapter);
        mListView.addHeaderView(headView);
        newsAdapter = new NewsAdapter(getActivity(), null);
        mListView.setAdapter(newsAdapter);
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage(getString(R.string.loading));
        progressDialog.setCancelable(true);
        setView(newsSectionVo.getNewsListVo(), true);
        Logger.i("父的ID:" + mClassId + "**子的ID:" + mZclassId);
        loadData(false, mClassId, mZclassId);
        headView.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                float dx = 0, dy = 0, ux, uy;
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        dx = event.getX();
                        dy = event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        // deltaY > 0 是向下运动,< 0是向上运动
                        ux = event.getX();
                        uy = event.getY();
                        if (Math.abs(dx - ux) < Math.abs(dy - uy)) {
                            mListView.onTouchEvent(event);
                        }
                }

                return false;
            }
        });
        return view;
    }

    private void initIndicator() {
        mExamplePagerAdapter = new ExamplePagerAdapter(titleList);//pageAdapter
        mViewPager.setAdapter(mExamplePagerAdapter);

        mcIndicator.setBackgroundColor(Color.WHITE);
        CommonNavigator commonNavigator = new CommonNavigator(getActivity());
        commonNavigator.setScrollPivotX(0.5f);
        commonNavigatorAdapter = new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return titleList == null ? 0 : titleList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                CommonPagerTitleView commonPagerTitleView = new CommonPagerTitleView(getActivity());
                View customLayout = LayoutInflater.from(getActivity()).inflate(R.layout.title_pager_child_newvideo, null);
                final TextView tv_pager_title = (TextView) customLayout.findViewById(R.id.tv_pager_title);
                tv_pager_title.setText(childList.get(index).getClass_name());
                tv_pager_title.setBackgroundColor(getResources().getColor(R.color.grey100));
                commonPagerTitleView.setContentView(customLayout);
                commonPagerTitleView.setOnPagerTitleChangeListener(new CommonPagerTitleView.OnPagerTitleChangeListener() {
                    @Override
                    public void onSelected(int index, int totalCount) {
                        tv_pager_title.setTextColor(getResources().getColor(R.color.white));
                        tv_pager_title.setBackgroundColor(getResources().getColor(R.color.red500));
                    }

                    @Override
                    public void onDeselected(int index, int totalCount) {
                        tv_pager_title.setTextColor(getResources().getColor(R.color.black));
                        tv_pager_title.setBackgroundColor(getResources().getColor(R.color.grey100));
                    }

                    @Override
                    public void onLeave(int index, int totalCount, float leavePercent, boolean leftToRight) {

                    }

                    @Override
                    public void onEnter(int index, int totalCount, float enterPercent, boolean leftToRight) {

                    }
                });
                commonPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //TODO 网络请求刷新数据
                        mViewPager.setCurrentItem(index);
                        mZclassId = childList.get(index).getClassid();//子ID
                        pageNo = 0;//切换将pageNo清零
                        currentPagePosition = 0;//将轮播图当前所在位置清零
                        Logger.i("父的ID:" + mClassId + "**子的ID:" + mZclassId);
                        loadData(false, mClassId, mZclassId);
                    }
                });
                return commonPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                return null;
            }
        };
        commonNavigator.setAdapter(commonNavigatorAdapter);
        mcIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(mcIndicator, mViewPager);
    }

    private void loadData(final boolean isShowDialog, String id, String zid) {

        if (!EquipmentUtil.checkNetState(getActivity())) {
            ((AbstractActivity) getActivity()).showShortToastMessage(getString(R.string.no_network));
            mListView.stopLoadMore();
            mListView.stopRefresh();
            return;
        }
        // pullToRefreshView.onHeaderRefreshComplete();
// pullToRefreshView.onFooterRefreshComplete();
// pullToRefreshView.onHeaderRefreshComplete();
// pullToRefreshView.onFooterRefreshComplete();
        newsListVoCallback = new ResultCallback(getActivity()) {
            @Override
            public void onSuccess(String response) {
                super.onSuccess(response);
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                // pullToRefreshView.onHeaderRefreshComplete();
                // pullToRefreshView.onFooterRefreshComplete();
                mListView.stopLoadMore();
                mListView.stopRefresh();
                NewsListVo2 result = JSON.parseObject(response, NewsListVo2.class);
                setView(result, false);
            }

            @Override
            public void onErrorCode(Exception e) {
                super.onErrorCode(e);
                // pullToRefreshView.onHeaderRefreshComplete();
                // pullToRefreshView.onFooterRefreshComplete();
                mListView.stopLoadMore();
                mListView.stopRefresh();
            }
        };
        RemoteImpl.getInstance().getNewsListVo2(this, id, zid, pageNo, pageSize).execute(newsListVoCallback);

    }

    private void setView(final NewsListVo2 result, boolean isCache) {
        if (result != null) {
            if (Code.CODE_SUCCESS != result.getCode() && !isCache) {

                Toast.makeText(getActivity(), result.getMessage(), Toast.LENGTH_SHORT).show();
                // pullToRefreshView.setEnablePullLoadMoreDataStatus(false);
                return;
            }

            newsSectionVo.setNewsListVo(result);
            if (newsSectionVo.getNewsListVo() != null && !newsSectionVo.getNewsListVo().getList().isEmpty()) {
                if (pageNo == 0) {
                    newsAdapter.clearData();
                }
                newsAdapter.addData(newsSectionVo.getNewsListVo().getList());
                // pullToRefreshView.setEnablePullLoadMoreDataStatus(true);
                mListView.setPullLoadEnable(true);
            } else if (!isCache) {
                // pullToRefreshView.setEnablePullLoadMoreDataStatus(false);
                mListView.setPullLoadEnable(false);
            }
            List<NewsBannerVo> bannerVos = result.getWheels();
            newsBannerPagerAdapter = new NewsBannerPagerAdapter(getActivity(), null);
            headPager.setAdapter(newsBannerPagerAdapter);
            newsBannerPagerAdapter.clearData();
            setView(bannerVos);
            newsBannerPagerAdapter.setData(result.getWheels());

        }
    }

    private void setView(final List<NewsBannerVo> bannerVos) {
        radioButtons.clear();
        radioGroup.removeAllViews();
        if (android.os.Build.VERSION.SDK_INT >= 11)
            mListView.removeHeaderView(headView);
        if (bannerVos == null || bannerVos.isEmpty()) {
            return;
        }

        try {
            mListView.addHeaderView(headView);
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (int i = 0, lenth = bannerVos.size(); i < lenth; i++) {
            RadioButton radioButton = (RadioButton) LayoutInflater.from(FlyApplication.context).inflate(R.layout.radiobutton, null);
            radioButtons.add(radioButton);
            radioButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        headPager.setCurrentItem(radioButtons.indexOf(buttonView));
                    }

                }
            });
            radioGroup.addView(radioButton);
        }
        if (radioGroup.getChildCount() > 1) {
            radioGroup.setVisibility(View.VISIBLE);
        } else {
            radioGroup.setVisibility(View.GONE);
        }

        headPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                currentPagePosition = position;
                ItktLog.i("headPager.onPageSelected:position==" + position);
                tvPageInfo.setText(bannerVos.get(position).getTitle());
                radioButtons.get(position).setChecked(true);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // Auto-generated method stub

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // Auto-generated method stub

            }
        });
        tvPageInfo.setText(bannerVos.get(currentPagePosition).getTitle());
        radioButtons.get(currentPagePosition).setChecked(true);

    }

    @Override
    public void onRefresh() {
        pageNo = 0;
        loadData(false, mClassId, mZclassId);
    }

    @Override
    public void onLoadMore() {
        pageNo++;
        loadData(false, mClassId, mZclassId);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
    }
}
